#include "stdafx.h"
#include "TIFfileData.h"
#include "processImageFns.h"
#include <iostream>
using namespace std;
short myShapenFileter[4][9] = {{0, 1, 0, 1, -4, 1, 0, 1, 0},
	{1, 1, 1, 1, -8, 1, 1, 1, 1},
	{0, -1, 0, -1, 4, -1, 0, -1, 0},
	{ -1, -1, -1, -1, 8, -1, -1, -1, -1}
};
TIFfileData::TIFfileData(const char* srcFileName, const char* dstFileName)
{
	FreeImage_Initialise(TRUE);
	loadTIFfile(srcFileName, dstFileName);
	processFileData();
}

bool TIFfileData::loadTIFfile(const char *srcfileName, const char* dstFileName)
{
	m_pSrcTIFfile = FreeImage_OpenMultiBitmap(FIF_TIFF, srcfileName, FALSE, FALSE, TRUE, 0);
	m_pDstTIFfile = FreeImage_OpenMultiBitmap(FIF_TIFF, dstFileName, TRUE, FALSE, TRUE, 0);

	if(!(m_pSrcTIFfile && m_pDstTIFfile))
	{
		cout << "load file failed" << endl;
		return false;
	}

	m_unPageCount = FreeImage_GetPageCount(m_pSrcTIFfile);
	m_pAyPage = new FIBITMAP*[m_unPageCount];
	return true;
}

void TIFfileData::proceePage(FIBITMAP* pPage)
{
	unsigned int imageWidth, imageHeight;
	imageHeight = FreeImage_GetHeight(pPage);
	imageWidth = FreeImage_GetWidth(pPage);
	cout << "bit number " << FreeImage_GetBPP(pPage) << endl;
	unsigned char *bitMapData = FreeImage_GetBits(pPage);
//	GamaRevert(bitMapData, imageWidth, imageHeight, 0.6);
	//BlackOrWhite(bitMapData, imageWidth, imageHeight);
	//MeanFilter(bitMapData, imageWidth, imageHeight, 3, 3);
//	MedianFilter(bitMapData, imageWidth, imageHeight, 3, 3);
	SharpenImage(bitMapData, imageWidth, imageHeight, myShapenFileter[4]);
}

void TIFfileData::processFileData()
{
	for(int i = 0; i < m_unPageCount; i++)
	{
		m_pAyPage[i] = FreeImage_LockPage(m_pSrcTIFfile, i);
		proceePage(m_pAyPage[i]);
		FreeImage_AppendPage(m_pDstTIFfile, m_pAyPage[i]);
		FreeImage_UnlockPage(m_pSrcTIFfile, m_pAyPage[i], false);
	}

	// Close src
	FreeImage_CloseMultiBitmap(m_pSrcTIFfile, 0);
	// Save and close dst
	FreeImage_CloseMultiBitmap(m_pDstTIFfile, TIFF_NONE);
}

TIFfileData::~TIFfileData()
{
	delete [] m_pAyPage;
	FreeImage_DeInitialise();
}
